'use strict';

let { User, SuperUser, Count, CountOption, CountShow, Statistics, StatisticsOption, Questionnaire } = require('../modles');
let auth = require('../utils/auth');

// 加载首页
let index_fn = async (ctx, next) => {
    let userId = ctx.session.userId;
    // ctx.session=null;
    // console.log("用户id是" + userId);
    console.log(userId);
    let user = await User.findOne({
        where: {
            id: userId
        }
    });

    let queForm = JSON.parse(JSON.stringify(await Questionnaire.findAll({
        where: {
            fromUserId: userId
        }
    })));


    // console.log(user.nickname);
    let nickname = user.nickname;

    let obj = {
        nickname: nickname,
        queForm: queForm
    }
    ctx.render('index.html', obj);
}

// 加载添加页
let add_fn = async (ctx, next) => {
    ctx.render('./add/add.html');
}

// 添加问卷页操作
let addDone_fn = async (ctx, next) => {
    let title = ctx.request.body.title || "";
    let presentation = ctx.request.body.presentation || "";
    let type = ctx.request.body.type || "";
    let fromUserId = ctx.session.userId;


    let ques = await Questionnaire.create({
        fromUserId: fromUserId,
        title: title,
        presentation: presentation,
        questionnaireType: type
    })

    let data = JSON.stringify(ques);

    let quforms = JSON.parse(JSON.stringify(await Questionnaire.findAll({
        where: {
            fromUserId: fromUserId,
            title: title,
            presentation: presentation,
            questionnaireType: type
        }
    })));

    let qusId;
    quforms.forEach(item => {
        qusId = item.id
    });

    ctx.body = { code: 200, data, msg: "填写成功啦！！！", id: qusId, type: type }
}

let addMassageStatistics_fn = async (ctx, next) => {
    let query = ctx.request.query;
    let id = query.id;
    if (id !== 0 && id !== undefined) {
        ctx.render('./add/addMessageStatistics.html');
    } else {
        ctx.render("./404.html")
    }
}

let addMassageStatisticsDone_fn = async (ctx, next) => {

}

// 加载添加统计分数问卷
let addMassageCount_fn = async (ctx, next) => {
    let query = ctx.request.query;
    let id = query.id;

    if (!isNaN(id)) {
        let queForm = JSON.parse(JSON.stringify(await Questionnaire.findAll({
            where: {
                id: id
            }
        })));
        if (queForm[0] !== undefined) {
            if (id != 0 && id !== undefined && id !== "") {
                let quenaire = JSON.parse(JSON.stringify(await Questionnaire.findAll({
                    where: {
                        id: id
                    }
                })));
                console.log(quenaire);
                let qneId;
                let qneTitle;
                let qnePresentation;
                let qneType;

                quenaire.forEach(item => {
                    qneId = item.id;
                    qneTitle = item.title;
                    qnePresentation = item.presentation;
                    qneType = item.questionnaireType;
                })

                let counts = JSON.parse(JSON.stringify(await Count.findAll({
                    where: {
                        fromQuestionnaireId: qneId
                    }
                })));

                let queIds = [];
                let queContents = [];
                counts.forEach(item => {
                    queIds.push(item.id);
                    queContents.push(item.countContent);
                });

                let countOptions = JSON.parse(JSON.stringify(await CountOption.findAll({
                    where: {
                        fromQuestionId: queIds
                    }
                })));

                let optIds = [];
                let optContents = [];
                let optTypes = [];

                countOptions.forEach(item => {
                    optIds.push(item.id);
                    optContents.push(item.optionContent);
                    optTypes.push(item.optionType);
                })

                counts.forEach(item => {
                    let opts = countOptions.filter(opt => {
                        return opt.fromQuestionId === item.id;
                    })[0];
                    // console.log("这是opts");
                    // console.log(opts.id);
                    // console.log(opts.optionContent);
                    // console.log(opts.optionType);

                    item.optId = opts.id;
                    item.optContents = opts.optionContent;
                    item.optTypes = opts.optionType;
                })
                console.log("底下是count");
                console.log(counts);
                console.log(counts[0]);
                let obj = {
                    qneTitle,
                    qnePresentation,
                    qneType,
                    counts,
                }
                ctx.render('./add/addMessageCount.html', obj);
            } else {
                ctx.render("./404.html")
            }
        } else {
            ctx.render("./404.html");
        }
    } else {
        ctx.render("./404.html");
    }
}

// 统计问卷添加输分题
let addScoreProblems_fn = async (ctx, next) => {
    let id = ctx.request.body.id || "";
    let type = 1;

    let counts = await Count.create({
        fromQuestionnaireId: id,
        countContent: "",
        countType: type
    })


    let data = JSON.stringify(counts);
    ctx.body = { code: 200, data, msg: "添加成功啦！！！" }

}

// 添加count选项
let addOptions_fn = async (ctx, next) => {
    let fromQuestionId = ctx.request.body.id || "";
    let optionContent = ctx.request.body.value || "";
    let optionType = ctx.request.body.type || "";

    let countOps = await CountOption.create({
        fromQuestionId: fromQuestionId,
        optionContent: optionContent,
        optionType: optionType
    })

    let data = JSON.stringify(countOps);
    ctx.body = { code: 200, data, msg: "成功" }
}

// 统计问卷添加选分题
let addSelectScore_fn = async (ctx, next) => {
    let id = ctx.request.body.id || "";
    let type = 2;

    let counts = await Count.create({
        fromQuestionnaireId: id,
        countContent: "",
        countType: type
    })


    let data = JSON.stringify(counts);
    ctx.body = { code: 200, data, msg: "添加成功啦！！！" }

}

// count提交
let countSubmit_fn = async (ctx, next) => {
    let subForm = ctx.request.body.subForm || "";
    let id = ctx.request.body.id || "";

    let subNameArr = [];
    let subValueArr = [];

    for (let sub in subForm) {
        subNameArr.push(sub);
        subValueArr.push(subForm[sub]);
    }

    let subType = [];
    let subId = [];

    for (let i = 0; i < subNameArr.length; i++) {
        let type = subNameArr[i].substring(0, 3);
        let id = subNameArr[i].slice(3);
        let value = subValueArr[i];
        subType.push(type);
        subId.push(id);
        if (type === "adq") {
            let addQues = await Count.update({
                countContent: value
            }, {
                where: {
                    id: id
                }
            });
        } else if (type === "ops") {
            let addOpts = await CountOption.update({
                optionContent: value
            }, {
                where: {
                    id: id
                }
            })
        }
    }
    ctx.body = { code: 200, msg: "添加成功啦！！！" }
}

// let countShowLoad_fn = async (ctx, next) => {
//     let id = ctx.request.body.id || "";
//     quesId=id;
// }

// 统计问卷展示页
let countShow_fn = async (ctx, next) => {
    let query = ctx.request.query;
    let id = query.id;

    if (!isNaN(id)) {

        let queForm = JSON.parse(JSON.stringify(await Questionnaire.findAll({
            where: {
                id: id
            }
        })));
        // console.log("看看");
        // console.log(queForm[0]);
        if (queForm[0] !== undefined) {
            if (id != 0 && id !== undefined && id !== "") {
                // console.log(id);
                if (id != null && id != "") {
                    let quenaire = JSON.parse(JSON.stringify(await Questionnaire.findAll({
                        where: {
                            id: id
                        }
                    })));
                    console.log(quenaire);
                    let qneId;
                    let qneTitle;
                    let qnePresentation;
                    let qneType;

                    quenaire.forEach(item => {
                        qneId = item.id;
                        qneTitle = item.title;
                        qnePresentation = item.presentation;
                        qneType = item.questionnaireType;
                    })

                    let counts = JSON.parse(JSON.stringify(await Count.findAll({
                        where: {
                            fromQuestionnaireId: qneId
                        }
                    })));
                    console.log("这是counts");
                    console.log(counts);
                    let queIds = [];
                    let queContents = [];
                    counts.forEach(item => {
                        queIds.push(item.id);
                        queContents.push(item.countContent);
                    });

                    let countOptions = JSON.parse(JSON.stringify(await CountOption.findAll({
                        where: {
                            fromQuestionId: queIds
                        }
                    })));

                    let optIds = [];
                    let optContents = [];
                    let optTypes = [];

                    countOptions.forEach(item => {
                        optIds.push(item.id);
                        optContents.push(item.optionContent);
                        optTypes.push(item.optionType);
                    })

                    counts.forEach(item => {
                        let opts = countOptions.filter(opt => {
                            return opt.fromQuestionId === item.id;
                        })[0];
                        // console.log("这是opts");
                        // console.log(opts.id);
                        // console.log(opts.optionContent);
                        // console.log(opts.optionType);

                        item.optId = opts.id;
                        item.optContents = opts.optionContent;
                        item.optTypes = opts.optionType;
                    })
                    // console.log("底下是count");
                    // console.log(counts);

                    let obj = {
                        qneTitle,
                        qnePresentation,
                        qneType,
                        counts,
                    }


                    ctx.render("./show/countShow.html", obj)
                } else {
                    console.log("你还没有添加题目");
                }
            } else {
                ctx.render("./404.html");
            }
        } else {
            ctx.render("./404.html");
        }
    } else {
        ctx.render("./404.html");
    }
}

// 统计问卷用户填表数据
let countShowSubmit_fn = async (ctx, next) => {
    let subForm = ctx.request.body.subForm || "";
    console.log(subForm);
    let subNameArr = [];
    let subValueArr = [];

    for (let sub in subForm) {
        subNameArr.push(sub);
        subValueArr.push(subForm[sub]);
    }

    let subType = [];
    let subId = [];

    let userId = ctx.session.userId;

    for (let i = 0; i < subNameArr.length; i++) {
        let type = subNameArr[i].substring(0, 3);
        let id = subNameArr[i].slice(3);
        let value = subValueArr[i];
        subType.push(type);
        subId.push(id);
        let showDemo = await CountShow.findOne({
            where: {
                fromUseId: userId,
                fromQuestionId: id,
            }
        });

        let u2Json = JSON.stringify(showDemo);
        console.log("打印");
        console.log(showDemo);
        console.log(u2Json);
        if (u2Json === "null") {
            console.log("添加");
            let addOptions = await CountShow.create({
                fromUseId: userId,
                fromQuestionId: id,
                score: value
            })
        } else {

            let showDemoId = showDemo.id;
            console.log("更新");
            console.log(showDemoId);
            let addOptions = await CountShow.update({
                score: value
            }, {
                where: {
                    id: showDemoId
                }
            })
        }
    }

    ctx.body = { code: 200, msg: "提交成功啦！！！" }
    // console.log(subId);
    // console.log(subType);

}

let showSubmitOk_fn = async (ctx, next) => {
    let query = ctx.request.query;
    let id = query.id;
    console.log(id);
    if (!isNaN(id)) {
        let queForm = JSON.parse(JSON.stringify(await Questionnaire.findAll({
            where: {
                id: id
            }
        })));
        console.log("看看");
        console.log(queForm[0]);
        if (queForm[0] !== undefined) {
            if (id != 0 && id !== undefined && id !== "") {
                ctx.render("./show/showSubmitOk.html")
            } else {
                ctx.render("./404.html")
            }
        } else {
            ctx.render("./404.html");
        }
    } else {
        ctx.render("./404.html");
    }

}

let addSubmitOk_fn = async (ctx, next) => {
    let query = ctx.request.query;
    let id = query.id;
    console.log(id);
    if (!isNaN(id)) {
        let queForm = JSON.parse(JSON.stringify(await Questionnaire.findAll({
            where: {
                id: id
            }
        })));
        console.log("看看");
        console.log(queForm[0]);
        if (queForm[0] !== undefined) {
            if (id != 0 && id !== undefined && id !== "") {
                ctx.render("./add/addSubmitOk.html")
            } else {
                ctx.render("./404.html")
            }
        } else {
            ctx.render("./404.html")
        }
    } else {
        ctx.render("./404.html")
    }

}

let share_fn = async (ctx, next) => {

}

let cancel_fn = async (ctx, next) => {

}

let login_fn = async (ctx, next) => {
    ctx.render("./login/login.html")
}
let loginDone_fn = async (ctx, next) => {
    let uid = ctx.request.body.username || "";
    let pwd = ctx.request.body.password || "";
    let res = '';
    if (uid.length > 0 && pwd.length > 0) {
        let row = await User.findOne({
            where: {
                username: uid,
                password: pwd
            }
        }
        )
        let u2Json = JSON.stringify(row);
        if (u2Json !== "null") {

            ctx.session.userId = row.id,
                ctx.session.userName = row.username,
                res = { code: 200, msg: "登陆成功！！！ " }
        } else {
            res = { code: 1000, msg: "用户名或密码错误，请重试！！！" }
        }
    } else {
        res = { code, msg: "用户名和密码不能为空 ！！！" }
    }
    ctx.body = JSON.stringify(res);
}

let register_fn = async (ctx, next) => {
    ctx.render("./login/register.html")
}

let registerDone_fn = async (ctx, next) => {
    let username = ctx.request.body.username || "";
    let nickname = ctx.request.body.nickname || "";
    let password = ctx.request.body.password || "";
    let confirmpassword = ctx.request.body.confirmpassword || "";
    // console.log(username);
    // console.log(password);
    // console.log(confirmpassword);
    if (username.length > 0 && password.length > 0 && confirmpassword.length > 0 && password === confirmpassword) {
        let userDemo = await User.findOne({ where: { username: username } });
        //console.log(JSON.stringify(userDemo));
        let res = '';

        let u2Json = JSON.stringify(userDemo);
        if (u2Json === 'null') {
            let u1 = await User.create({
                username: username,
                password: password,
                nickname: nickname
            });
            let u1Json = JSON.stringify(u1);
            if (u1Json !== 'null') {
                res = { code: 200, msg: '用户注册成功！！！' };
            } else {
                res = { code: 1000, msg: '因为服务器或者网络原因，用户未注册成功！！！' };
            }
        } else {
            res = { code: 1000, msg: '当前用户名已经注册，请确认后重试！！！' };
        }

        ctx.body = JSON.stringify(res);
        // ctx.render('login.html');
    } else {
        console.log('用户名或密码不能为空；并且两次密码应该相同！！！');
    }
}

let logout_fn = async (ctx, next) => {
    ctx.session = null;
    ctx.body = { code: 200, msg: '注销成功' };
}

let show_fn = async (ctx, next) => {
    ctx.render("./show.html")
    let userId = ctx.session.userId;
    let query = ctx.request.query;
    let id = Number(query.id);
    console.log(id);

    
    // console.log(queForm[0]);

    if (id != 0 && id !== undefined && id !== "") {
        if (!isNaN(id)) {
            // 返回id正确
            let quenaire = JSON.parse(JSON.stringify(await Questionnaire.findAll({
                where: {
                    id: id
                }
            })));
            if (quenaire[0] !== undefined) {

                let qneId;
                let qneTitle;
                let qnePresentation;
                let qneType;

                quenaire.forEach(item => {
                    qneId = item.id;
                    qneTitle = item.title;
                    qnePresentation = item.presentation;
                    qneType = item.questionnaireType;
                })
                console.log(qneId);
                console.log(qneTitle);
                console.log(qnePresentation);
                console.log(qneType);

                let cots = JSON.parse(JSON.stringify(await Count.findAll({
                    where: {
                        fromQuestionnaireId: qneId
                    }
                })));
                
                console.log("这是cots");
                console.log(cots);
                let counts = JSON.parse(JSON.stringify(await Count.findAll({
                    where: {
                        fromQuestionnaireId: qneId
                    }
                })));
                console.log("最开始的counts");
                console.log(counts);

                let queIds = [];
                let queContents = [];
                counts.forEach(item => {
                    queIds.push(item.id);
                    queContents.push(item.countContent);
                });

                console.log(queIds);

                // let newcounts = JSON.parse(JSON.stringify(await Count.findAll({
                //     where: {
                //         id: queIds
                //     }
                // })));
                // console.log("这是newcounts");
                // console.log(newcounts);
                console.log("准备countshow");
                console.log("准备counts");
                console.log(counts);
                let countShows = JSON.parse(JSON.stringify(await CountShow.findAll({
                    where: {
                        fromQuestionId: queIds
                    }
                })));

                console.log("底下是countShows");
                console.log(countShows);
                console.log("底下是countShow长度");

                console.log(countShows.length);
                for (let i = 0; i < countShows.length; i++) {
                    countShows.forEach(item => {
                        let questions = cots.filter(qus => {
                            console.log(qus.id);
                            console.log(item.fromQuestionId);
                            return qus.id = item.fromQuestionId
                        })[i];
                        console.log("打印questions");
                        console.log(questions);
                        
                        
                        item.ShowContent = questions.countContent;
                    });
                }
                console.log("底下是countShows");
                console.log(countShows);
                let ShowIds = [];
                let countScore = [];
                countShows.forEach(item => {
                    ShowIds.push(item.fromUseId);
                    countScore.push(item.score)
                })


                console.log("最后");
                console.log(counts);
                console.log(counts.length);
                for (let i = 0; i < counts.length; i++) {
                    counts.forEach(item => {
                        let shows = countShows.filter(show => {
                            return show.fromQuestionId === queIds[i];
                        })[0];
                        console.log(shows);

                        item.ShowScore = shows.score;
                        item.ShowUserId = shows.fromUseId;
                    })
                }
                console.log("底下是count");
                console.log(counts);
                let ques = JSON.parse(JSON.stringify(await Questionnaire.findAll({
                    where: {
                        fromUserId: userId
                    }
                })));
                console.log(ques);
                let quesTitle = [];
                ques.forEach(item => {
                    quesTitle.push(item.title);
                })
                console.log(quesTitle);
                console.log(counts.ShowUserId);
                // let countUserId = [];
                // let countScore = [];
                // counts.forEach(item => {
                //     countUserId.push(item.ShowUserId);
                //     countScore.push(item.ShowScore);
                // })


                let showsScore = JSON.parse(JSON.stringify(await CountShow.findAll({
                    where: {
                        fromQuestionId: queIds
                    }
                })));

                console.log("分数");
                console.log(countScore);
                let countScoreAll = 0;
                for (let i = 0; i < countScore.length; i++) {
                    countScoreAll += Number(countScore[i]);
                }

                let users = JSON.parse(JSON.stringify(await User.findAll({
                    where: {
                        id: ShowIds
                    }
                })));
                console.log("下面用户表");
                console.log(users);

                let obj = {
                    users,
                    ques,
                    quesTitle,
                    counts,
                    countScoreAll,
                    countShows
                }
                ctx.render("./show.html", obj)
            } else {
                ctx.render("./404.html")
            }
        } else {
            // ctx.render("./show.html")
            let ques = JSON.parse(JSON.stringify(await Questionnaire.findAll({
                where: {
                    fromUserId: userId
                }
            })));
            console.log(ques);
            let quesTitle = [];
            ques.forEach(item => {
                quesTitle.push(item.title);
            })
            let obj = {
                ques
            }
            ctx.render("./show.html", obj)
        }
    } else {
        ctx.render("./show.html")
    }




}

let showDone_fn = async (ctx, next) => {
    console.log("ssds");
    let questionnaireId = ctx.request.body.questionnaireId || "";

    console.log(questionnaireId);
}

// let noget_fn = async (ctx, next) => {
//     ctx.render("./404.html")
// }




module.exports = {
    "/": ["get", auth, index_fn],
    "/add": ["get", auth, add_fn],
    "/addDone": ["post", addDone_fn],
    "/addMessageStatistics": ["get", addMassageStatistics_fn],
    "/addMessageStatisticsDone": ["post", addMassageStatisticsDone_fn],
    "/addMessageCount": ["get", auth, addMassageCount_fn],
    "/addScoreProblems": ["post", addScoreProblems_fn],
    "/addOptions": ["post", addOptions_fn],
    "/addSelectScore": ["post", addSelectScore_fn],
    "/countSubmit": ["post", countSubmit_fn],
    // "/countShowLoad": ["post", countShowLoad_fn],
    "/countShow": ["get", auth, countShow_fn],
    "/countShowSubmit": ["post", countShowSubmit_fn],
    "/showSubmitOk": ["get", auth, showSubmitOk_fn],
    "/addSubmitOk": ["get", auth, addSubmitOk_fn],
    "/share": ["post", share_fn],
    "/cancel": ["post", cancel_fn],
    "/login": ["get", auth, login_fn],
    "/loginDone": ["post", loginDone_fn],
    "/register": ["get", register_fn],
    "/registerDone": ["post", registerDone_fn],
    "/logout": ["post", auth, logout_fn],
    "/show": ["get", auth, show_fn],
    "/showDone": ["post", showDone_fn],
    // "/404":["get",auth,noget_fn]

}